package org.vergil.rest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.vergil.core.service.UserService;
import org.vergil.dto.Jwt;
import org.vergil.dto.User;
import org.vergil.utils.JwtUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * Created by vergil on 17-4-4.
 */
@RestController
public class LoginRestFul {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public Map<String, Object> login(@RequestBody Map user) {
        Map<String, Object> result = new HashMap<>();
        if (user.containsKey("username") && user.containsKey("loginPassword")) {
            Optional<String> jwt = Optional.ofNullable(
                    userService.getUserToken(user.get("username").toString(), user.get("loginPassword").toString()));
            jwt.ifPresent(value -> result.put("jwt", value));
            result.put("info", 1);
        }
        return result;
    }

    @RequestMapping("/register")
    public Map register(@RequestBody Map userMap) {
        Map<String, Object> result = new HashMap<>();
        Long userId = 1L;
        if (userMap.containsKey("username") && userMap.containsKey("registerPassword")) {
            User user = new User();
            user.setUsername(userMap.get("username").toString());
            user.setPassword(userMap.get("registerPassword").toString());
            userId = userService.insert(user);
        }
        if (!userId.equals(0L)) {
            result.put("info", 1);
            result.put("jwt", "alex");
        } else {
            result.put("info", 2);
        }
        return result;
    }

    @RequestMapping("/logout")
    public Map logout(HttpServletRequest request){
        Map<String, Object> result = new HashMap<>();
        String jwtContext = request.getHeader("jwt");
        if (null == jwtContext && !"".equals(jwtContext)){
            return result;
        }
        Jwt jwt = JwtUtils.decodeJwt(jwtContext);
        if (userService.logout(jwt)) {
            result.put("info", 1);
        }
        return result;
    }
}
